package com.csj.mvvm.utils

import android.annotation.SuppressLint
import android.text.TextUtils
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Matcher
import java.util.regex.Pattern


object TimeUtil {
    /**
     * 时间格式化
     *
     * @param millis
     * @param template
     * @return
     */
    fun getStringTime(millis: Long, template: String): String {
        val format = SimpleDateFormat(template, Locale.getDefault())
        return format.format(millis)
    }

    /**
     * 时间戳转换为时间
     * 服务器返回的时间戳是10位的,必须自己添加最后3位
     *
     * @param time
     * @param template
     * @return
     */
    fun getStringTime(time: String, template: String): String {
        if (TextUtils.isEmpty(time) || "0" == time) {
            return ""
        }
        if (!isNumber(time)) {
            return time
        }
        val format = SimpleDateFormat(template, Locale.getDefault())
        val millis = if (time.length < 13) {
            (time + "000").toLong()
        } else {
            time.toLong()
        }
        return format.format(millis)
    }

    /**
     * 判断是否是正整数
     *
     * @param str
     * @return
     */
    fun isNumber(str: String): Boolean {
        val strPattern = "^[\\d]*$"
        val p: Pattern = Pattern.compile(strPattern)
        val m: Matcher = p.matcher(str)
        return m.matches()
    }

    fun getLongTime(timeString: String, template: String): Long {
        val format = SimpleDateFormat(template, Locale.getDefault())
        val d: Date
        return try {
            d = format.parse(timeString)
            d.time
        } catch (e: Exception) {
            0L
        }
    }

    /**
     * @param millis
     * @return
     */
    fun getWeek(millis: Long): String? {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = millis
        calendar[Calendar.HOUR_OF_DAY] = 0
        calendar[Calendar.MINUTE] = 0
        calendar[Calendar.SECOND] = 0
        calendar[Calendar.MILLISECOND] = 0
        var week: String? = null
        when (calendar[Calendar.DAY_OF_WEEK]) {
            Calendar.MONDAY -> week = "星期一"
            Calendar.TUESDAY -> week = "星期二"
            Calendar.WEDNESDAY -> week = "星期三"
            Calendar.THURSDAY -> week = "星期四"
            Calendar.FRIDAY -> week = "星期五"
            Calendar.SATURDAY -> week = "星期六"
            Calendar.SUNDAY -> week = "星期日"
        }
        return week
    }

    /**
     * 日期转最近时间
     */
    fun friendlyTime(time: Date): String {
        //获取time距离当前的秒数
        val ct = ((System.currentTimeMillis() - time.time) / 1000).toInt()
        if (ct == 0) {
            return "刚刚"
        }
        if (ct in 1..59) {
            return ct.toString() + "秒前"
        }
        if (ct in 60..3599) {
            return (ct / 60).coerceAtLeast(1).toString() + "分钟前"
        }
        if (ct in 3600..86399) return (ct / 3600).toString() + "小时前"
        if (ct in 86400..2591999) { //86400 * 30
            return (ct / 86400).toString() + "天前"
        }
        return if (ct in 2592000..31103999) {
            (ct / 2592000).toString() + "月前"
        } else (ct / 31104000).toString() + "年前"
    }

    /**
     * 秒转成HH:MM:SS
     */
    fun changeHMS(second: Int): String {
        var h = 0
        var d = 0
        var s = 0
        val temp = second % 3600
        if (second > 3600) {
            h = second / 3600
            if (temp != 0) {
                if (temp > 60) {
                    d = temp / 60
                    if (temp % 60 != 0) {
                        s = temp % 60
                    }
                } else {
                    s = temp
                }
            }
        } else {
            d = second / 60
            if (second % 60 != 0) {
                s = second % 60
            }
        }
        return builder(
            if (h > 9) h.toString() else "0$h",
            ":",
            if (d > 9) d.toString() else "0$d",
            ":",
            if (s > 9) s.toString() else "0$s"
        )
    }

    fun builder(vararg array: String): String {
        val s = StringBuilder()
        for (str in array) {
            s.append(str)
        }
        return s.toString()
    }

    private var dayTab = arrayOf(
        intArrayOf(
            0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        ),
        intArrayOf(
            0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
        )
    )

    fun dayOfYear(month: Int, days: Int, year: Int): Int {
        var day = days
        val leap: Int
        leap = if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) 1 else 0
        var i = 1
        while (i < month) {
            day += dayTab[leap][i]
            i++
        }
        return day
    }

    /**
     * 今年的第几天
     */
    fun dayOfYear(month: Int, days: Int): Int {
        var day = days
        val year: Int = getCurrDate("yyyy").toInt()
        val leap: Int
        leap = if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) 1 else 0
        var i = 1
        while (i < month) {
            day += dayTab[leap][i]
            i++
        }
        return day
    }

    /**
     * 今年的几月几日
     */
    fun getDateByDay(days: Int): String {
        // k月份，leap判断是否闰年（0非闰年1闰年）
        var day = days
        val leap: Int
        val year: Int = getCurrDate("yyyy").toInt()
        leap = if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) 1 else 0
        var k = 1
        while (day > dayTab[leap][k]) {
            day -= dayTab[leap][k]
            k++
        }
        return k.toString() + "月" + day + "日"
    }

    /**
     * 获取系统当前日期
     */
    @SuppressLint("SimpleDateFormat")
    fun getCurrDate(format: String): String {
        val curDate = Date(System.currentTimeMillis()) //获取当前时间
        return SimpleDateFormat(format).format(curDate)
    }
}